package com.gykfbxxh.imovie.custom.net;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.app.utils.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gykfbxxh.imovie.base.bean.DataBean;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.manager.AppConfigManager;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 制作一个 gson的post请求
 * Makes a post request and converts the response from JsonElement into a
 * list of objects/object using with Google Gson.
 * Created by xuxinghai on 2016/6/12.
 */
public class GsonPostRequest<T> extends Request<T> {
    private final Gson gson;
    private final Type type;
    private final Response.Listener<T> listener;
    private Map<String, String> mParms;


    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url           URL of the request to make
     * @param type          is the type of the object to be returned
     * @param listener      is the listener for the right answer
     * @param errorListener is the listener for the wrong answer
     */
    public GsonPostRequest
    (
            @NonNull final String url,
            @NonNull Map<String, String> parms,
            @NonNull final Type type,
            @NonNull final Gson gson,
            @NonNull final Response.Listener<T> listener,
            @NonNull final Response.ErrorListener errorListener
    ) {
        super(Method.POST, url, errorListener);
        this.gson = gson;
        this.type = type;
        this.listener = listener;
        this.mParms = parms;
    }

    @Override
    public String getCacheKey() {
        if (mParms != null) {
            Object[] key = mParms.keySet().toArray();
            if (key == null || key.length == 0) {
                //如果没有参数 返回源链接
                return super.getCacheKey();
            }
            StringBuffer cacheKey = new StringBuffer(super.getCacheKey() + "?");
            for (int i = 0; i < key.length; i++) {
                if (mParms.get(key[i]) != null) {
                    cacheKey.append(key[i] + "=" + mParms.get(key[i]).toString() + "&");
                } else {
                    cacheKey.append(key[i] + "=null&");
                }
            }
            return cacheKey.toString();
        }
        return super.getCacheKey();
    }

    @Override
    protected void deliverResponse(T response) {
        if (listener != null) {
            listener.onResponse(response);
        }
    }


    @Override
    public void deliverError(VolleyError error) {

        if (error instanceof NoConnectionError) {
            //如果没有网络则读取缓存
            Cache.Entry entry = this.getCacheEntry();
            if (entry != null) {
                Response<T> response = parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
                deliverResponse(response.result);
                return;
            }
        }
        super.deliverError(error);

    }


    /**
     * 有可能返回null
     * @param response Response from the network
     * @return
     */
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {

        try {
            /**
             * 获取用户Token
             */
            Map<String, String> headers = response.headers;
            String headerValue = headers.get("Set-Cookie");
            if (!TextUtils.isEmpty(headerValue)) {
                String[] tokens = headerValue.split(";");
                for (int i = 0; i < tokens.length; i++) {
                    String token = tokens[i].trim();
                    if (token.equals("no-cache") || token.equals("no-store")) {
                        break;
                    } else if (token.startsWith("mortise_loginToken=")) {
                        try {
                            String tokenStr = token.substring(19);
                            if(!TextUtils.isEmpty(tokenStr)) {
                                LogUtils.e("xuxh","LoginToken="+tokenStr);
                                AppConfigTools.TOKENSTR = tokenStr ;
                                SharedPreferences.Editor editor = AppConfigManager.getInstance().getEditor();
                                editor.putString(ConfigKey.user_token,tokenStr);
                                editor.commit();
                            }
                        } catch (Exception e) {
                        }
                    }
                }
            }
//            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            String json = new String(response.data);
            if (TextUtils.isEmpty(json)) {
                json = DataBean.getDefaultJson();
            }

            /**
             * 如果解析的json为 空字符串或者null，返回null 执行成功的回调函数
             * 目前json不为空,成功的回调函数返回值不为null
             * 如果解析的json格式不对，执行失败的回调函数
             * 如果type为null执行失败的回调函数
             */
            return (Response<T>) Response.success
                    (

                            gson.fromJson(json, type),
                            HttpHeaderParser.parseCacheHeaders(response)

                    );
        }
//        catch (UnsupportedEncodingException e)
//        {
//            return Response.error(new ParseError(e));
//        }
        catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParms;
    }


    /**
     * header
     *
     * @return
     * @throws AuthFailureError
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> head = new HashMap<>();
//        head.put("ms", URIContant.getComonUriParms());//接口公共的参数
//        head.put("cv", AppTools.getVersionName());//接口识别码
//        head.put("referer", URIContant.REALMNAME);//接口域名
//        if (UserInforManager.getInstance().getUserInfor() != null
//                && !TextUtils.isEmpty(UserInforManager.getInstance().getUserInfor().getToken())) {
//            head.put("token", UserInforManager.getInstance().getUserInfor().getToken());
//        }
        if(TextUtils.isEmpty(AppConfigTools.TOKENSTR)) {
            String tokenStr = AppConfigManager.getInstance().readConfig(ConfigKey.user_token, "");
            if(!TextUtils.isEmpty(tokenStr)) {
                head.put("Cookie","mortise_loginToken="+tokenStr);
            }
        }else {
            head.put("Cookie","mortise_loginToken="+AppConfigTools.TOKENSTR);
        }
        return head;


    }

}
